package com.osfw.framework.directive;

import com.osfw.system.service.config.ISysConfigService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;

/**
 * 参数设置信息获取指令
 */
@Component
public class ConfigDirective implements TemplateDirectiveModel {


    @Autowired
    private ISysConfigService tempConfigService;
    private static ISysConfigService configService;

    @PostConstruct
    public void init() {
        configService = this.tempConfigService;
    }

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        if (map.containsKey("key") && map.get("key") != null) {
            String key = map.get("key").toString();
            String config = configService.selectConfigByKey(key);
            if(config == null){
                config = "";
            }
            environment.setVariable("config", builder.build().wrap(config));
        }
        if (templateDirectiveBody != null) {
            templateDirectiveBody.render(environment.getOut());
        }
    }
}
